package com.efounder.message.socket;

import com.efounder.util.AppContext;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

import org.apache.commons.lang3.StringUtils;

public class TCPClientSSLContextFactory
{
    private static final String KEY_STORE_TYEP= "BKS";
    private static final String TRUST_KEY_STORE_TYEP = "BKS";
    
	private static final String PROTOCOL = "TLS";
 


    private  String clientKeyStore = "client.bks";;
    
    private  String clientKeyStorePassword= "zangyanke";
    
    private  String clientTrustKeyStore= "ca.bks";
    
    private  String clientTrustKeyStorePassword= "zangyanke";
    
    private SSLContext clientContext;

    public void init()
    {
        SSLContext context = null;
        try {
            if(StringUtils.isEmpty(clientKeyStore)||StringUtils.isEmpty(clientTrustKeyStore))
            {
                return;
            }
            InputStream ksin = AppContext.getInstance().getAssets().open(clientKeyStore);
            KeyStore ks = KeyStore.getInstance(KEY_STORE_TYEP);
            ks.load(ksin, clientKeyStorePassword.toCharArray());
           
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
            kmf.init(ks, clientKeyStorePassword.toCharArray());

            InputStream tin = AppContext.getInstance().getAssets().open(clientTrustKeyStore);
            KeyStore tks = KeyStore.getInstance(TRUST_KEY_STORE_TYEP);
            tks.load(tin, clientTrustKeyStorePassword.toCharArray());
            
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
            tmf.init(tks);
            
            context = SSLContext.getInstance(PROTOCOL);
            context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        } catch (Exception e) {
            throw new Error("Failed to initialize the server-side SSLContext", e);
        }
        this.clientContext = context;
    }

    public  SSLContext getClientContext() {
        return clientContext;
    }



}
